package com.jintoufs.weixin.finance;

import com.jintoufs.domain.account.Withdraw;
import com.jintoufs.domain.constants.MessageConstants;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.service.account.WithdrawService;
import com.jintoufs.service.customer.CustomerService;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.weixin.SupportAction;
import io.swagger.annotations.Api;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Api
@RestController
@RequestMapping("/api/finance")
public class FinanceAction extends SupportAction{
    @Resource
    private WithdrawService withdrawService;

    @Resource
    private CustomerService customerService;
    @GetMapping("doFinance")
    public AjaxMsg doFinance(Withdraw withdraw,String token,String price){
        AjaxMsg ajaxMsg = new AjaxMsg();
        Customer customer = customerService.getByToken(token);
        if (ValidUtil.isEmpty(customer)) {
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(MessageConstants.SYSTEM_ERROR_MESSAGE);
            return ajaxMsg;
        }
        try {
            withdraw.setId(getUUID());
            withdraw.setCustomerId(customer.getId());
            withdraw.setShopId(customer.getRecommendId());
            withdraw.setPrice(new BigDecimal(price));
            BigDecimal newDivided = customer.getDivided().subtract(withdraw.getPrice());
            if(newDivided.compareTo(new BigDecimal("0"))<0){
                //提现金额不合法
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("余额不足");
                return ajaxMsg;
            }
            withdrawService.insert(withdraw);
            customer.setDivided(newDivided);
            //更新分润金额
            customerService.update(customer);
            ajaxMsg.setDatas(newDivided.toString());
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setMessage("服务器错误");
            ajaxMsg.setCode(AjaxMsg.FAILURE);
        }
        return ajaxMsg;
    }


    @GetMapping("financeList")
    public AjaxMsg financeList(String token){
        AjaxMsg ajaxMsg = new AjaxMsg();
        Customer customer = getCustomerByToken(token);
        if (!ValidUtil.isEmpty(customer)){
            Map<String,Object> param = new HashMap<>();
            param.put("customerId",customer.getId());
            ajaxMsg.setDatas(withdrawService.getByParams(param));
        }else {
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("用户校验失败");
        }

        return ajaxMsg;

    }
}
